# 图片和短信验证码

from rest_framework.views import APIView
from django_redis import get_redis_connection
from django.http import HttpResponse
from rest_framework.generics import GenericAPIView
import random
from rest_framework.response import Response
from rest_framework import status
import logging

from meiduo_mall.apps.verifications import constants
from meiduo_mall.libs.captcha.captcha import captcha
from . import serializers
from meiduo_mall.libs.yuntongxun.sms import CCP
from celery_tasks.sms.tasks import send_sms_code
# Create your views here.


# 日志记录器
logger = logging.getLogger('django')


# url('^sms_codes/(?P<mobile>1[3-9]\d{9})/$', views.SMSCodeView.as_view()),
class SMSCodeView(GenericAPIView):
    """短信验证码"""

    # 指定序列化器
    serializer_class = serializers.ImageCodeCheckSerializer

    def get(self, request, mobile):
        """发送短信验证码"""

        # 实例化序列化器对象，用于校验图片验证码是否正确和60s内发送短信是否频繁
        # mobile被放在类视图对象的kwargs属性中,用于读取是否60s内频繁发送短信
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        # 校验通过：生成短信验证码和发送短信
        # 生成短信验证码（0-999999）
        sms_code = '%06d' % random.randint(0,999999)
        logger.debug(sms_code)

        # 发送短信
        # result = CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_TEMPLATE_EXPIRES], constants.SMS_CODE_TEMPLATE_ID)
        # if result != 0:
        #     return Response({'message':'发送短信验证码失败'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        # 使用celery异步发送短信
        send_sms_code.delay(mobile, sms_code)


        # 获取连接到redis的对象
        redis_conn = get_redis_connection('verify_codes')

        # 使用redis管道操作redis:提升redis数据库访问性能
        pl = redis_conn.pipeline()
        # 存储短信验证码到redis
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 短信发送记录标记
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        # 执行
        pl.execute()

        # 响应发送短信验证码结果
        return Response({'message':'OK'})


# url('^image_codes/(?P<image_code_id>[\w-]+)/$', views.ImageCodeView.as_view()),
class ImageCodeView(APIView):
    """图片验证码"""

    def get(self, request, image_code_id):
        """提供图片验证码"""

        # 生成验证码图片
        text, image = captcha.generate_captcha()

        redis_conn = get_redis_connection("verify_codes")
        redis_conn.setex("img_%s" % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)

        # 固定返回验证码图片数据，不需要REST framework框架的Response帮助我们决定返回响应数据的格式
        # 所以此处直接使用Django原生的HttpResponse即可
        return HttpResponse(image, content_type="images/jpg")